<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="shopCart in shopInfoList"
          :key="shopCart.skuId"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="!!shopCart.isChecked"
              @change="checkCarInfoState(shopCart)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="shopCart.imgUrl" />
            <div class="item-msg">
              {{ shopCart.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ shopCart.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeSkuNum('decrement', shopCart)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="shopCart.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('change', shopCart, $event)"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="changeSkuNum('increment', shopCart)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ shopCart.skuPrice * shopCart.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:void(0);"
              class="sindelet"
              @click="showDialogByDelOneCartInfo(shopCart.skuId)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDialogByDelSelectedCartInfo"
          >删除选中的商品</a
        >
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ selectCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectMoney }}</i>
        </div>
        <div class="sumbtn">
          <router-link to="/trade" class="sum-btn">结算</router-link>
        </div>
      </div>
    </div>

    <!-- 弹出的弹窗 -->
    <!-- <Dialog v-show="isShow" @close="closeDialog"> -->
    <!-- <Dialog :visible="isShow" @close:visible="closeDialog"> -->
    <!-- <Dialog :visible="isShow" @close:visible="isShow = $event"> -->
    <Dialog :visible.sync="isShow">
      <!-- 头部具名插槽 -->
      <template v-slot:header>
        <div>
          <p>提示</p>
        </div>
      </template>
      <!-- 中部默认插槽 -->
      <template>
        <div>您真的确定要删除{{ isDelOne ? "此件" : "所选的" }}商品吗？</div>
      </template>
      <!-- 底部具名插槽 -->
      <template #footer>
        <div class="btn-footer">
          <button class="btn btn-cancle" @click="isShow = false">取消</button>
          <button class="btn btn-primary" @click="delShopCartInfo">确认</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqGetShopList,
  reqChangeCartState,
  reqChangeAllCartState,
  reqDelOneShopCartInfo,
  reqDelSelectedShopCartInfo,
  reqAddOrUpdateCart,
} from "../../api";
// import Dialog from "@/components/Dialog";
import { skuNumReg } from "@/utils/ref";

export default {
  name: "ShopCart",
  // components: { Dialog },
  data() {
    return {
      shopInfoList: [], //储存购物车要渲染的商品
      isShow: false, //是否显示
      skuId: "", //存储要删除商品的ID
      isDelOne: false, // 是否删除一条
      skuIdList: [], //储存要批量删除商品的Id
      timeId: 0, //存储定时器Id
      num: 0, //存储订单商品数量
    };
  },
  methods: {
    // 获取/更新购物车数据
    async getShopCartListData() {
      const result = await reqGetShopList();
      if (result.code === 200) {
        this.shopInfoList = result.data.length
          ? result.data[0].cartInfoList
          : [];
      }
    },
    // 改变商品是否被选中
    async checkCarInfoState(shopCart) {
      let isChecked = 1 - shopCart.isChecked;
      const result = await reqChangeCartState(shopCart.skuId, isChecked);
      if (result.code === 200) {
        // 更新服务器数据成功后，重新更新页面
        shopCart.isChecked = isChecked;
      } else {
        console.log(result.message);
      }
    },
    // 点击删除单向商品是调用的方法
    showDialogByDelOneCartInfo(skuId) {
      // 显示弹窗
      this.isShow = true;
      // 储存Id
      this.skuId = skuId;
      // 显示只删除一项
      this.isDelOne = true;
    },
    // 点击删除所选商品时调用的函数
    async showDialogByDelSelectedCartInfo() {
      // 显示弹窗
      this.isShow = true;
      // 将是否删除一条改为否
      this.isDelOne = false;
      // 存储所选项的Id
      this.skuIdList = [];

      // 存储Id
      this.shopInfoList.forEach(
        (item) => item.isChecked && this.skuIdList.push(item.skuId)
      );
    },
    // 点击弹窗确认删除商品时调用的方法
    async delShopCartInfo() {
      if (this.isDelOne) {
        // 删除单条商品
        const result = await reqDelOneShopCartInfo(this.skuId);
        if (result.code === 200) {
          // 正常发送请求
          // this.getShopCartListData();
          // 偷懒方式
          this.shopInfoList = this.shopInfoList.filter(
            (item) => item.skuId !== this.skuId
          );
          this.isShow = false;
        } else {
          alert("删除失败！！");
        }
        return;
      }
      // 删除所选商品
      const result = await reqDelSelectedShopCartInfo(this.skuIdList);
      console.log(result);
      if (result.code === 200) {
        // 正常发送请求
        // this.getShopCartListData();
        // 自个写的 麻烦
        // this.shopInfoList = this.shopInfoList.filter((item) => {
        //   if (this.skuIdList.include(item.skuId)) return;
        //   return item;
        // });
        // 简写
        this.shopInfoList = this.shopInfoList.filter(
          (item) => item.isChecked === 0
        );

        this.isShow = false;
      } else {
        alert("删除失败！！");
      }
    },
    // 更新商品数量
    changeSkuNum(type, shopCart, e) {
      // let num = 0;
      // 判断求出商品改变的数量
      // 保存一开始的商品数
      const oldNum = shopCart.skuNum;
      switch (type) {
        case "increment":
          this.num++;
          shopCart.skuNum++;
          if (shopCart.skuNum > 200) {
            this.num = 200 - oldNum;
            shopCart.skuNum = 200;
          }
          // if (shopCart.skuNum < 200) {
          //   num++;
          //   shopCart.skuNum++;
          // }
          break;
        case "decrement":
          if (shopCart.skuNum > 1) {
            this.num--;
            shopCart.skuNum--;
          }
          break;
        case "change":
          let newNum = e.target.value; // 用户新输入的数据
          // let oldNum = shopCart.skuNum;
          if (skuNumReg.test(newNum)) {
            shopCart.skuNum = newNum;
            this.num = newNum - oldNum;
            if (newNum > 200) {
              shopCart.skuNum = 200;
              this.num = 200 - oldNum;
            }
          } else {
            e.target.value = oldNum;
          }
          break;
      }

      if (this.num === 0) return;
      // 开启商品数量防抖
      if (this.timeId) clearTimeout(this.timeId);
      this.timeId = setTimeout(async () => {
        const result = await reqAddOrUpdateCart(shopCart.skuId, this.num);
        if (result.code === 200) {
          this.num = 0; //将num重置为0，重新统计
          console.log("更改数据成功...");
        } else {
          console.log("更改数据失败...");
        }
      }, 500);
    },
  },
  computed: {
    // 是否全选
    checkAll: {
      get() {
        return (
          this.shopInfoList.every((item) => item.isChecked === 1) &&
          this.shopInfoList.length
        );
      },
      async set(val) {
        // 将全选全不选框取反
        let isChecked = val ? 1 : 0;
        let skuIdList = []; //用于保存要修改的id
        this.shopInfoList.forEach((item) => {
          item.isChecked = isChecked;
          skuIdList.push(item.skuId);
        });

        const result = await reqChangeAllCartState(isChecked, skuIdList);
        if (result.code === 200) {
          // alert("更新成功...");
        } else {
          console.log("更新失败...");
        }
      },
    },
    // 统计选中商品的总数量
    selectCount() {
      return this.shopInfoList.reduce(
        (prev, current) => prev + current.isChecked,
        0
      );
    },
    // 统计选中商品的总金额
    selectMoney() {
      return this.shopInfoList.reduce(
        (prev, current) =>
          prev + current.skuNum * current.skuPrice * current.isChecked,
        0
      );
    },
  },
  mounted() {
    this.getShopCartListData();
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}

// 插槽样式
.btn-footer {
  position: absolute;
  right: 16px;
  bottom: 20px;
  .btn {
    width: 70px;
    height: 36px;
    margin-right: 12px;
    cursor: pointer;
    border: none;
    font-size: 14px;
    border-radius: 8%;
    &.btn-cancle {
      border: 1px solid #ccc;
      &:hover {
        background-color: #ecf5ff;
        color: #47a2ff;
      }
    }
    &.btn-primary {
      background-color: #409eff;
      color: #fff;
      &:hover {
        background-color: #66b1ff;
      }
    }
  }
}
</style>
